package common.store.admin.contoller;


import common.store.common.util.C3p0Pool;
import common.store.common.util.MD5;
import common.store.web.bean.User;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/adminLogin")
public class AdminLoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = MD5.stringMD5(req.getParameter("password"));
        if (username == null || password == null){
            req.setAttribute("msg" , "用户名或密码不能为空！");
            req.getRequestDispatcher("admin/index.jsp").forward(req , resp);
        }
        QueryRunner qr = new QueryRunner(C3p0Pool.getDataSource());
        try {
            User user = qr.query("select u.uid , u.name, u.state from user u where username = ? and password = ?"
                    , new BeanHandler<>(User.class) , username , password);
            if (user == null){
                req.setAttribute("msg", "用户名或密码错误！");
                req.getRequestDispatcher("admin/index.jsp").forward(req , resp);
            }
            if (user.getState() != 1){
                req.setAttribute("msg", "该用户不是管理员！");
                req.getRequestDispatcher("admin/index.jsp").forward(req , resp);
            }

            HttpSession session = req.getSession();
            session.setAttribute("user" , user);

            req.getRequestDispatcher("admin/home.jsp").forward(req , resp);


        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
